package com.example.viewmodelstudio.lifeclcycle_service;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

public class GetPositioningUtils {
    private Context me;
    private static GetPositioningUtils getPositioningUtils;
    private LocationManager locationManager;
    private int page = 0;

    public static GetPositioningUtils getInstance() {
        if (getPositioningUtils == null) {
            getPositioningUtils = new GetPositioningUtils();
        }
        return new GetPositioningUtils();
    }

    public GetPositioningUtils getContext(Context me) {
        this.me = me;
        return this;
    }

    //纬度 newLocation.getLatitude();
    //经度 newLocation.getLongitude()
    public void getLocation(LocationIf locationIf) {
        locationManager = (LocationManager) me.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(me, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(me, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        String bestProvider = locationManager.getBestProvider(getCriteria(), true);
        locationManager.requestLocationUpdates(bestProvider, 5000, 8, new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                locationIf.getLocationData(location);
            }

            @Override
            public void onProviderDisabled(String provider) {
                locationIf.getLocationData(null);
            }

            @Override
            public void onProviderEnabled(String provider) {
                if (ActivityCompat.checkSelfPermission(me, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(me, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                locationIf.getLocationData(locationManager.getLastKnownLocation(provider));
            }
        });
    }


    private Criteria getCriteria() {
        Criteria c = new Criteria();
        c.setAccuracy(Criteria.ACCURACY_COARSE);
        c.setSpeedRequired(false);
        c.setCostAllowed(false);
        c.setBearingRequired(false);
        c.setAltitudeRequired(false);
        c.setPowerRequirement(Criteria.POWER_LOW);
        return c;
    }

    public interface LocationIf {
        void getLocationData(Location location);
    }


}
